package cxydmmszl.chapter01.t003;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Stack;

/**
 * 如何仅用递归函数和栈操作逆序一个栈
 * @author habitplus
 * @since 2021-08-13 11:01
 */
public class Main {
    /**
     * 将栈底元素移除并返回
     */
    private static int getAndRemoveLastElement(Stack<Integer> stack) {
        int result = stack.pop();

        if (stack.isEmpty()) {
            return result;
        } else {
            int last = getAndRemoveLastElement(stack);
            stack.push(result);
            return last;
        }
    }

    /**
     * 逆序一个栈
     */
    public static void reverse(Stack<Integer> stack) {
        if (stack.isEmpty()) return;

        int i = getAndRemoveLastElement(stack);
        reverse(stack);
        stack.push(i);
    }

    private static final StreamTokenizer st =
            new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

    static int nextInt() {
        try {
            st.nextToken();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return (int) st.nval;
    }

    public static void main(String[] args) {
        int n = nextInt();
        Stack<Integer> stack = new Stack<>();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = nextInt();
        }

        for (int i = n-1; i >= 0; i--) {
            stack.push(arr[i]);
        }

        reverse(stack);

        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) {
            sb.append(stack.pop()).append(" ");
        }
        System.out.println(sb.toString());
    }
}
